package com.tiantian.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.tiantian.common.annotation.Log;
import com.tiantian.common.constant.Constants;
import com.tiantian.common.core.domain.LoginBody;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.domain.entity.SysUser;
import com.tiantian.common.core.domain.model.LoginUser;
import com.tiantian.common.enums.BusinessType;
import com.tiantian.common.helper.LoginHelper;
import com.tiantian.system.service.ISysUserService;
import com.tiantian.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录验证
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    @Log(title = "用户登录", businessType = BusinessType.LOGIN)
    public ResponseResult<Map<String, Object>> login(@Validated @RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ResponseResult.ok(ajax);
    }

    /**
     * 获取token信息
     */
    @GetMapping("/getTokenInfo")
    public ResponseResult<SaTokenInfo> test() {
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return ResponseResult.ok(tokenInfo);
    }


    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @SaIgnore
    public ResponseResult<Void> logout() {
        loginService.logout();
        return ResponseResult.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    @SaCheckLogin
    public ResponseResult<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("userInfo", user);
        ajax.put("role", loginUser.getRoleDTO());
        ajax.put("permissions", loginUser.getPermissions());
        return ResponseResult.ok(ajax);
    }

}
